from flask import Blueprint, request, jsonify, session, render_template
from datetime import datetime
from app.extensions import db
from app.models.user import CoupleRelationship, User, CoupleRequest, SharedAnniversary
from app.routes.api import login_required, login_required_html

couple_bp = Blueprint('couple_bp', __name__)


@couple_bp.route('/api/couple/relationship', methods=['GET'])
@login_required
def get_relationship_status():
    """获取    获取当前用户的情侣关系状态
    """
    user_id = session['user_id']

    # 查找当前用户参与的情侣关系
    relationship = CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == user_id) |
         (CoupleRelationship.user2_id == user_id)) &
        (CoupleRelationship.status == 'accepted')
    ).first()

    if not relationship:
        return jsonify({
            'in_relationship': False
        })

    # 确定伴侣ID
    partner_id = relationship.user2_id if relationship.user1_id == user_id else relationship.user1_id
    partner = User.query.get(partner_id)

    # 计算在一起的天数
    days_together = (datetime.utcnow() - relationship.accepted_at).days

    return jsonify({
        'in_relationship': True,
        'relationship': {
            'id': relationship.id,
            'days_together': days_together,
            'started_at': relationship.accepted_at.isoformat()
        },
        'partner': {
            'id': partner.id,
            'username': partner.username,
            'nickname': partner.nickname,
            'avatar': partner.avatar
        }
    })


@couple_bp.route('/api/couple/requests', methods=['GET'])
@login_required
def get_couple_requests():
    """
    获取当前用户的所有情侣请求（收到的和发送的）
    """
    user_id = session['user_id']

    # 获取收到的请求
    received_requests = CoupleRequest.query.filter_by(
        receiver_id=user_id
    ).all()

    # 获取发送的请求
    sent_requests = CoupleRequest.query.filter_by(
        sender_id=user_id
    ).all()

    # 格式化收到的请求
    formatted_received = []
    for req in received_requests:
        sender = User.query.get(req.sender_id)
        formatted_received.append({
            'id': req.id,
            'sender_id': req.sender_id,
            'sender_name': sender.nickname,
            'sender_avatar': sender.avatar,
            'message': req.message,
            'status': req.status,
            'created_at': req.created_at.isoformat()
        })

    # 格式化发送的请求
    formatted_sent = []
    for req in sent_requests:
        receiver = User.query.get(req.receiver_id)
        formatted_sent.append({
            'id': req.id,
            'receiver_id': req.receiver_id,
            'receiver_name': receiver.nickname,
            'receiver_avatar': receiver.avatar,
            'message': req.message,
            'status': req.status,
            'created_at': req.created_at.isoformat()
        })

    return jsonify({
        'received': formatted_received,
        'sent': formatted_sent
    })


@couple_bp.route('/api/couple/request', methods=['POST'])
@login_required
def send_couple_request():
    """
    发送情侣请求
    """
    data = request.json
    receiver_username = data.get('receiver_username')
    message = data.get('message', '')

    if not receiver_username:
        return jsonify({'status': 'error', 'message': '请输入对方用户名'}), 400

    # 查找接收者
    receiver = User.query.filter_by(username=receiver_username).first()
    if not receiver:
        return jsonify({'status': 'error', 'message': '用户不存在'}), 404

    sender_id = session['user_id']

    # 不能向自己发送请求
    if receiver.id == sender_id:
        return jsonify({'status': 'error', 'message': '不能向自己发送请求'}), 400

    # 检查是否已经是情侣
    existing_relationship = CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == sender_id) &
         (CoupleRelationship.user2_id == receiver.id)) |
        ((CoupleRelationship.user1_id == receiver.id) &
         (CoupleRelationship.user2_id == sender_id))
    ).first()

    if existing_relationship:
        return jsonify({'status': 'error', 'message': '你们已经是情侣了'}), 400

    # 检查是否已有未处理的请求
    existing_request = CoupleRequest.query.filter(
        ((CoupleRequest.sender_id == sender_id) &
         (CoupleRequest.receiver_id == receiver.id)) |
        ((CoupleRequest.sender_id == receiver.id) &
         (CoupleRequest.receiver_id == sender_id))
    ).filter_by(status='pending').first()

    if existing_request:
        return jsonify({'status': 'error', 'message': '已有未处理的请求'}), 400

    # 创建新请求
    new_request = CoupleRequest(
        sender_id=sender_id,
        receiver_id=receiver.id,
        message=message,
        status='pending',
        created_at=datetime.utcnow()
    )

    db.session.add(new_request)
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '请求已发送',
        'request_id': new_request.id
    })


@couple_bp.route('/api/couple/request/<int:request_id>/respond', methods=['POST'])
@login_required
def respond_to_request(request_id):
    """
    回应情侣请求（接受或拒绝）
    """
    data = request.json
    action = data.get('action')  # 应为 'accept' 或 'reject'

    if action not in ['accept', 'reject']:
        return jsonify({'status': 'error', 'message': '无效的操作'}), 400

    user_id = session['user_id']

    # 获取请求
    couple_request = CoupleRequest.query.filter_by(
        id=request_id,
        receiver_id=user_id,
        status='pending'
    ).first()

    if not couple_request:
        return jsonify({'status': 'error', 'message': '请求不存在或已处理'}), 404

    # 更新请求状态
    couple_request.status = 'accepted' if action == 'accept' else 'rejected'
    couple_request.responded_at = datetime.utcnow()

    if action == 'accept':
        # 创建情侣关系，确保user1_id < user2_id以避免重复关系
        user1_id = min(couple_request.sender_id, user_id)
        user2_id = max(couple_request.sender_id, user_id)

        new_relationship = CoupleRelationship(
            user1_id=user1_id,
            user2_id=user2_id,
            status='accepted',
            accepted_at=datetime.utcnow()
        )

        db.session.add(new_relationship)

    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': f'已{"接受" if action == "accept" else "拒绝"}请求'
    })


@couple_bp.route('/api/couple/request/<int:request_id>', methods=['DELETE'])
@login_required
def cancel_request(request_id):
    """
    取消已发送的情侣请求
    """
    user_id = session['user_id']

    # 查找请求
    couple_request = CoupleRequest.query.filter_by(
        id=request_id,
        sender_id=user_id,
        status='pending'
    ).first()

    if not couple_request:
        return jsonify({'status': 'error', 'message': '请求不存在或已处理'}), 404

    # 删除请求
    db.session.delete(couple_request)
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '请求已取消'
    })


@couple_bp.route('/api/couple/relationship', methods=['DELETE'])
@login_required
def end_relationship():
    """
    解除情侣关系
    """
    user_id = session['user_id']

    # 查找关系
    relationship = CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == user_id) |
         (CoupleRelationship.user2_id == user_id)) &
        (CoupleRelationship.status == 'accepted')
    ).first()

    if not relationship:
        return jsonify({'status': 'error', 'message': '没有找到情侣关系'}), 404

    # 先删除所有关联的共享纪念日
    shared_anniversaries = SharedAnniversary.query.filter_by(
        relationship_id=relationship.id
    ).all()
    for anniversary in shared_anniversaries:
        db.session.delete(anniversary)

    # 直接删除数据库中的关系记录
    db.session.delete(relationship)
    db.session.commit()
    return jsonify({
        'status': 'success',
        'message': '情侣关系已解除'
    })


def get_relationship_or_404(user_id):
    """获取用户的情侣关系，不存在则返回404"""
    relationship = CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == user_id) |
         (CoupleRelationship.user2_id == user_id)) &
        (CoupleRelationship.status == 'accepted')
    ).first()

    if not relationship:
        return jsonify({'status': 'error', 'message': '没有找到情侣关系'}), 404

    return relationship


@couple_bp.route('/api/couple/shared-anniversaries', methods=['GET'])
@login_required
def get_shared_anniversaries():
    """获取情侣共同的纪念日"""
    user_id = session['user_id']

    # 获取情侣关系
    relationship = get_relationship_or_404(user_id)
    if isinstance(relationship, tuple):  # 检查是否是错误响应
        return relationship

    # 获取所有共同纪念日并按日期排序
    anniversaries = SharedAnniversary.query.filter_by(
        relationship_id=relationship.id
    ).order_by(SharedAnniversary.date).all()

    # 转换为字典列表并返回
    return jsonify({
        'anniversaries': [anniv.to_dict() for anniv in anniversaries]
    })


# 纪念日相关API
@couple_bp.route('/api/anniversaries', methods=['GET'])
@login_required
def get_anniversaries():
    user_id = session['user_id']

    # 获取情侣关系
    relationship = get_relationship_or_404(user_id)
    if isinstance(relationship, tuple):  # 检查是否是错误响应
        return relationship

        # 获取所有共同纪念日并按日期排序
    anniversaries = SharedAnniversary.query.filter_by(
        relationship_id=relationship.id
    ).order_by(SharedAnniversary.date).all()
    return jsonify([{
        'id': a.id,
        'title': a.title,
        'date': a.date,
        'type': a.type,
        'description': a.description,
        'created_at': a.created_at.isoformat()
    } for a in anniversaries])


# 纪念日相关API
@couple_bp.route('/api/couple/shared-anniversaries/<int:anniv_id>', methods=['GET'])
@login_required
def get_one_anniversaries(anniv_id):
    user_id = session['user_id']

    # 获取纪念日
    anniversary = SharedAnniversary.query.get(anniv_id)
    if not anniversary:
        return jsonify({'status': 'error', 'message': '纪念日不存在'}), 404

    # 验证用户是否有权限（必须是该情侣关系的成员）
    relationship = get_relationship_or_404(user_id)
    if isinstance(relationship, tuple):  # 检查是否是错误响应
        return relationship

    if anniversary.relationship_id != relationship.id:
        return jsonify({'status': 'error', 'message': '无权修改此纪念日'}), 403
    return jsonify({"anniversary": {
        'id': anniversary.id,
        'title': anniversary.title,
        'date': anniversary.date,
        'type': anniversary.type,
        'description': anniversary.description,
        'created_at': anniversary.created_at.isoformat()
    }})


@couple_bp.route('/api/couple/shared-anniversaries', methods=['POST'])
@login_required
def add_shared_anniversary():
    """添加共同纪念日"""
    user_id = session['user_id']
    data = request.json

    # 验证必要字段
    required_fields = ['title', 'date']
    for field in required_fields:
        if field not in data or not data[field]:
            return jsonify({'status': 'error', 'message': f'请提供{field}'}), 400

    # 验证日期格式
    try:
        datetime.strptime(data['date'], '%Y-%m-%d')
    except ValueError:
        return jsonify({'status': 'error', 'message': '日期格式不正确，请使用YYYY-MM-DD'}), 400

    # 获取情侣关系
    relationship = get_relationship_or_404(user_id)
    if isinstance(relationship, tuple):  # 检查是否是错误响应
        return relationship

    # 创建新的共同纪念日
    new_anniv = SharedAnniversary(
        relationship_id=relationship.id,
        title=data['title'],
        date=data['date'],
        type=data.get('type', ''),
        description=data.get('description', ''),
        created_by=user_id
    )

    db.session.add(new_anniv)
    db.session.commit()
    return jsonify({
        'status': 'success',
        'message': '共同纪念日添加成功',
        'anniversary': new_anniv.to_dict()
    })


@couple_bp.route('/api/couple/shared-anniversaries/<int:anniv_id>', methods=['PUT'])
@login_required
def update_shared_anniversary(anniv_id):
    """更新共同纪念日"""
    user_id = session['user_id']
    data = request.json

    # 获取纪念日
    anniversary = SharedAnniversary.query.get(anniv_id)
    if not anniversary:
        return jsonify({'status': 'error', 'message': '纪念日不存在'}), 404

    # 验证用户是否有权限（必须是该情侣关系的成员）
    relationship = get_relationship_or_404(user_id)
    if isinstance(relationship, tuple):  # 检查是否是错误响应
        return relationship

    if anniversary.relationship_id != relationship.id:
        return jsonify({'status': 'error', 'message': '无权修改此纪念日'}), 403

    # 验证日期格式（如果提供了日期）
    if 'date' in data and data['date']:
        try:
            datetime.strptime(data['date'], '%Y-%m-%d')
        except ValueError:
            return jsonify({'status': 'error', 'message': '日期格式不正确，请使用YYYY-MM-DD'}), 400

    # 更新字段
    if 'title' in data:
        anniversary.title = data['title']
    if 'date' in data:
        anniversary.date = data['date']
    if 'type' in data:
        anniversary.type = data['type']
    if 'description' in data:
        anniversary.description = data['description']

    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '共同纪念日更新成功',
        'anniversary': anniversary.to_dict()
    })


@couple_bp.route('/api/couple/shared-anniversaries/<int:anniv_id>', methods=['DELETE'])
@login_required
def delete_shared_anniversary(anniv_id):
    """删除共同纪念日"""
    user_id = session['user_id']

    # 获取纪念日
    anniversary = SharedAnniversary.query.get(anniv_id)
    if not anniversary:
        return jsonify({'status': 'error', 'message': '纪念日不存在'}), 404

    # 验证用户是否有权限
    relationship = get_relationship_or_404(user_id)
    if isinstance(relationship, tuple):  # 检查是否是错误响应
        return relationship

    if anniversary.relationship_id != relationship.id:
        return jsonify({'status': 'error', 'message': '无权删除此纪念日'}), 403

    # 删除纪念日
    db.session.delete(anniversary)
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '共同纪念日已删除'
    })


# 在couple.py蓝图中添加页面路由
@couple_bp.route('/couple')
@login_required_html
def couple_page():
    """渲染情侣空间页面"""
    return render_template('couple.html')
